package com.xky.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    private static final Properties PROPERTIES = new Properties();
    static {

        InputStream resourceAsStream = DBUtils.class.getResourceAsStream("/application.properties");
        if (resourceAsStream == null) {
            throw new RuntimeException("无法加载数据库配置文件");
        }

        try {
            PROPERTIES.load(resourceAsStream);
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载数据库配置或驱动失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }


    /**
     * 配置数据库连接信息
     * @return
     */
    public static Connection getConnection(){
        Connection connection;

        try {
          connection =  DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
        if (connection!=null){
            System.out.println("数据库已连接成功，数据正在刷新！");
        }else {
            System.out.println("数据库连接失败!");
        }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 释放资源（遵循先开后关的原则）
     * @param connection
     * @param preparedStatement
     * @param resultSet
     */
    public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        DBUtils.getConnection();
    }
}
